import { useUserStore } from '@/store'
const rc: any = uni.getRecorderManager()
// 录音开始时间
let startTime = null

const start = () => {
  return new Promise((resolve, reject) => {
    rc.onStart(() => {
      startTime = new Date()
      resolve({})
    })
    rc.onError((e) => {
      console.log(e)
      reject(e)
    })
    rc.start({
      format: 'aac', // 录音格式，可选值：aac/mp3
    })
  })
}

const pause = () => {
  rc.stop()
}

const close = () => {
  rc.stop()
}

const upload = () => {
  return new Promise((resolve, reject) => {
    rc.onStop((wavFile: { tempFilePath: any }, _a: any, _b: any) => {
      const userStore = useUserStore()
      uni.uploadFile({
        url: '/resource/oss/upload', // 替换为实际的上传接口
        filePath: wavFile.tempFilePath,
        header: {
          Authorization: `Bearer ${userStore.userInfo.token}`,
          clientId: `Bearer ${userStore.userInfo.ClientId}`,
        },
        name: 'file',
        success: (res) => {
          const r = JSON.parse(res.data)
          console.log('r======', r)
          if (r.code === 200) {
            const duration = (new Date().getTime() - startTime.getTime()) / 1000
            const data = {
              duration: Math.round(duration),
              url: r.data,
            }
            resolve(data)
          } else {
            reject(new Error(r.msg))
          }
        },
        fail: (e) => {
          reject(e)
        },
      })
    })
  })
}

export { start, pause, close, upload }
